const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

//封装request请求
const showText = (a, b) => {
  wx.showToast({
    title: a,
    icon: b,
  })
}
const app = getApp()
const sendRequest = (url, method = 'GET', data = {}, tokenType = 0, contentType) => {
  var userToken = wx.getStorageSync('Authorization') || '';
  var ownerToken = wx.getStorageSync('OwnerInfo').Authorization || '';
  // console.log(wx.getStorageSync('OwnerInfo').Authorization)
  // console.log(tokenType)
  return new Promise(function (resolve, reject) {
    wx.request({
      url: `${app.globalData.urls}api/${url}`,
      data: data,
      method: method,
      header: {
        'Content-Type': contentType ? contentType : 'application/x-www-form-urlencoded',
        'Authorization': tokenType === 0 ? userToken : ownerToken
      },
      success: function (res) {
        if (res.header.Authorization) {
          wx.setStorageSync('token', res.header.Authorization);
        }
        var code = res.statusCode;
        switch (code) {
          case 401:
            wx.showModal({
              title: '登录提示',
              content: '身份已过期，请重新登录并授权',
              success(res) {
                if (res.confirm) {
                  // wx.navigateTo({
                  //   url: '/pages/accredit/accredit',
                  // })
                }
              }
            })
            break;
          case 402:
            showText('该用户账号被冻结', 'none');
            break;
          case 403:
            wx.showModal({
              title: '温馨提示',
              content: '请认证后再来操作！',
              success(res) {
                if (res.confirm) {
                  wx.navigateTo({
                    url: '../register/register',
                  })
                }
              }
            })
            break;
          case 422:
            var msg = res.msg;
            wx.showToast({
              title: msg,
              icon: 'none'
            });
            resolve(res);
            break;
          case 500:
            wx.showModal({
              title: '异常提示',
              content: '请求500，请重新登录',
              showCancel: false,
              success(res) {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '../accredit/accredit',
                  })
                }
              }
            })
            break;
          default:
            resolve(res);
            break;
        }
      },
      fail: function (err) {
        reject(err);
      }
    })
  })
}

module.exports = {
  formatTime,
  sendRequest
}